from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import json
from ..utils.jwt_utils import generate_token, verify_token
from ..utils.response import success_response, error_response
from ..utils.log_utils import log_operation
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
import hashlib

@csrf_exempt
@require_http_methods(["POST"])
def admin_login(request):
    print("admin_login")
    
    try:
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return error_response('用户名和密码不能为空')
            
        # 使用Django的authenticate进行用户验证
        user = authenticate(username=username, password=password)
        if not user:
            return error_response('用户名或密码错误')
            
        # 检查用户权限
        if not user.is_staff:
            return error_response('无权限访问')
            
        # 生成token
        token = generate_token(user.id)
        
        # 记录登录操作
        log_operation(user.id, 'admin_login', f'管理员 {username} 登录成功')
        
        return success_response({
            'token': token,
            'user_info': {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'first_name': user.first_name,
                'last_name': user.last_name,
                'is_superuser': user.is_superuser,
                'is_staff': user.is_staff,
                'last_login': user.last_login
            }
        })
    except Exception as e:
        return error_response(str(e))

@require_http_methods(["POST"])
def admin_logout(request):
    try:
        # 验证token
        user_id = verify_token(request)
        if not user_id:
            return error_response('未登录或登录已过期')
            
        # 记录登出操作
        log_operation(user_id, 'admin_logout', '管理员登出')
        
        return success_response('登出成功')
    except Exception as e:
        return error_response(str(e))

@require_http_methods(["GET"])
def admin_info(request):
    try:
        token = request.headers.get('Authorization')
        # 验证token
        # return success_response({
        #     'id': 333
        # })
        user_id = verify_token(token)
        print(user_id)
        if not user_id:
            return error_response('未登录或登录已过期')
        
        # 获取用户信息
        user = User.objects.get(id=user_id)
        
        
        return success_response({
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'first_name': user.first_name,
            'last_name': user.last_name,
            'is_superuser': user.is_superuser,
            'is_staff': user.is_staff,
            'last_login': user.last_login,
            'date_joined': user.date_joined
        })
    except User.DoesNotExist:
        return error_response('用户不存在')
    except Exception as e:
        return error_response(str(e))

@csrf_exempt
@require_http_methods(["POST"])
def admin_change_password(request):
    try:
        # 验证token
        user_id = verify_token(request)
        if not user_id:
            return error_response('未登录或登录已过期')
            
        data = json.loads(request.body)
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        
        if not old_password or not new_password:
            return error_response('旧密码和新密码不能为空')
            
        # 获取用户信息
        user = User.objects.get(id=user_id)
        
        # 验证旧密码
        if not user.check_password(old_password):
            return error_response('旧密码错误')
            
        # 更新密码
        user.set_password(new_password)
        user.save()
        
        # 记录修改密码操作
        log_operation(user_id, 'admin_change_password', '管理员修改密码')
        
        return success_response('密码修改成功')
    except User.DoesNotExist:
        return error_response('用户不存在')
    except Exception as e:
        return error_response(str(e)) 